package gw.com.android.presenter.http;

import android.text.TextUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.utils.CacheUtils;
import okhttp3.Request;
import okhttp3.Response;
import www.com.library.app.Logger;

/**
 * @author jett
 * @since 2018-08-30.
 */
public class ReferenceRequest {

    private final String TAG = "ReferenceRequest";

    private int currentPage;
    private int pageSize = 10;
    private int totalSize = -1;

    public List<Data> fetchLocal() {
        String str = CacheUtils.readFile("market_reference.data");
        return parse(str, false);
    }

    public void getList(final HttpCallback<List<Data>> callback) {
        Logger.i(TAG, "");
        totalSize = -1;
        currentPage = 1;
        sendRequest(currentPage, callback);
    }

    public void nextPage(final HttpCallback<List<Data>> callback) {
        sendRequest(++currentPage, callback);
    }

    private void sendRequest(final int page, final HttpCallback<List<Data>> callback) {
        String url = "https://openapi.hxfx.com/hx/";
        new Https(url)
                .addParam("service", "Advisory.getType")
                .addParam("companyId", ConfigUtil.instance().mConfigObject.optString(ConfigType.COMPANY_ID_TAG)) // 2:hx9999, 9:hxfx, 13:8bx,18:ft
                .addParam("pageSize", String.valueOf(pageSize))
                .addParam("page", String.valueOf(page))
                .addParam("utmTerminal", "app")
                .get(new Https.ResponseCallback<String>() {
                    @Override
                    public void onSuccess(Request request, Response response, String result, int code) {
                        Logger.i(TAG, "onSuccess url = " + request.url().toString());
                        List<Data> data = parse(result, page == 1);
                        if (callback != null) {
                            callback.onSuccess(data);
                        }
                    }

                    @Override
                    public void onFailure(Request request, IOException e) {
                        Logger.e(TAG, e);
                        if (page > 1) {
                            currentPage--;
                        }
                        if (callback != null) {
                            callback.onFailure(e);
                        }
                    }
                });
    }

    public boolean hasNextPage() {
        if (totalSize > 0) {
            return (totalSize - 1) / pageSize > currentPage - 1;
        }
        return false;
    }

    private List<Data> parse(String str, boolean cacle) {
        if (TextUtils.isEmpty(str)) {
            return null;
        }
        try {
            JSONObject jsonObject = new JSONObject(str);
            JSONObject dataJson = jsonObject.optJSONObject("data");
            if (dataJson != null) {
                totalSize = dataJson.optInt("count");
                JSONArray listJson = dataJson.optJSONArray("list");
                if (listJson != null && listJson.length() > 0) {
                    List<Data> list = new ArrayList<>();
                    for (int i = 0; i < listJson.length(); i++) {
                        JSONObject json = listJson.optJSONObject(i);
                        if (json != null) {
                            Data data = new Data();
                            data.title = json.optString("title");
                            data.label = json.optString("label");
                            data.cover_img = json.optString("coverImg");
                            data.release_time = json.optString("releaseTime");
                            list.add(data);
                        }
                    }
                    return list;
                }
                if (cacle) {
                    CacheUtils.writeFile("market_reference.data", str);
                }
            }
        } catch (JSONException e) {
            Logger.e(TAG, e);
        }
        return null;
    }

    public class Data {
        public String title;
        public String label;
        public String cover_img;
        public String release_time;
    }

}
